/*
 * sys.c - Syscalls implementation
 */

#include <devices.h>
#include <utils.h>
#include <errno.h>
#include <types.h>

void sys_ni_syscall() {
    
}

int sys_write(int fd,char *buffer, int size)
{
    if (size == 0) return 0;
	//COMPROBAR CANAL Y OPERACION SEAN VALIDAS
	int res = 0;// = comprova_fd(fd, ESCRIPTURA);
	//COMPROBAR QUE EL PUNTERO A BUFFER SEA CORRECTO
	if (buffer == NULL)
		return -EFAULT;
	//COMPROBAR QUE EL NUMERO DE CARACTERES A ESCRIBIR SEA VALIDO
	if (size < 0)
		return -EINVAL;
	if (res < 0)
		return res;
		
	//comienza la escritura
	int writed = 0;
	char buff[256]; 	
	while( size > 0 && buffer[writed] != NULL && res == 0)
	{
		if(size < 256)
		{
			res = copy_from_user(buffer+writed, &buff, size);
			if(res == 0)
			{
				res = sys_write_console(&buff, size);
				if(res < 0 )
					return -EIO;
				else
				{
					size-=res;
					writed += res;
				}
			}
			else
				return -EINVAL;
		}
		else
		{
			res = copy_from_user(buffer+writed, &buff, 256);
			if(res == 0)
			{
				res = sys_write_console(&buff, 256);
				if(res < 0 )
					return -EIO;
				else
				{
					size-=256;
					writed += 256;
				}
			}
			else
				return -EINVAL;
		
		}
	}
	return writed;
}

